package com.mf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mf.Enum.UserTransferAccountsType;
import com.mf.entity.User;
import com.mf.entity.UserTransferAccounts;
import com.mf.exception.CustomExceptionHandler;
import com.mf.mapper.UserMapper;
import com.mf.mapper.UserTransferAccountsMapper;
import com.mf.service.IUserTransferAccountsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户转账记录表 服务实现类
 * </p>
 *
 * @author mf
 * @since 2024-05-19
 */
@Service
public class UserTransferAccountsServiceImpl extends ServiceImpl<UserTransferAccountsMapper, UserTransferAccounts> implements IUserTransferAccountsService {
    @Resource
    private UserTransferAccountsMapper userTransferAccountsMapper;

    @Resource
    private UserMapper usersMapper;

    @Override
    public Integer add(UserTransferAccounts userTransferAccounts) {
        // 获取当前用户账户情况
        final LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId, userTransferAccounts.getUserId());
        final User user = usersMapper.selectOne(userLambdaQueryWrapper);

        // 买入新增用户金额 反之卖出减少用户金额
        if (userTransferAccounts.getType().equals(UserTransferAccountsType.IN)) {
            user.setMoney(user.getMoney().add(userTransferAccounts.getAmount()));
        } else {
            // 如果转出金额小于用户金额，则抛出异常
            if (userTransferAccounts.getAmount().compareTo(user.getMoney()) > 0) {
                throw new CustomExceptionHandler("转出金额大于用户金额");
            }
            user.setMoney(user.getMoney().subtract(userTransferAccounts.getAmount()));
        }
        // 保存转账记录

        // 更新用户金额
        usersMapper.update(user,userLambdaQueryWrapper);
        return userTransferAccountsMapper.insert(userTransferAccounts);
    }
}
